from django.contrib.auth.models import User
from rest_framework import serializers

from .models import Department, Position, Role


class DepartmentSerializer(serializers.ModelSerializer):
    # 可以不做这个,知道了leader_id,在user表中可以找到对应的信息
    leader_name = serializers.SerializerMethodField()

    class Meta:
        model = Department
        fields = "__all__"

    def get_leader_name(self, obj):
        try:
            user = User.objects.get(id=obj.leader_id)
        except Exception:
            return None
        return user.last_name


class PositionSerializer(serializers.ModelSerializer):
    class Meta:
        model = Position
        fields = "__all__"


class RoleSerializer(serializers.ModelSerializer):
    department = DepartmentSerializer()
    position = PositionSerializer()

    class Meta:
        model = Role
        fields = "__all__"
